<template>
	<view class="page friends-page">
		<!-- 自定义导航栏 -->
		<br>
		<ob-navbar title="好友管理" :show-back="true" />
		<br>

		<view class="content">
			<!-- 好友申请通知 -->
			<view class="request-notice" @click="goToRequests">
				<view class="notice-icon">R</view>
				<view class="notice-info">
					<text class="notice-title">好友申请</text>
					<text class="notice-desc">{{ pendingRequests }}条好友申请</text>
				</view>
				<text class="notice-arrow">></text>
			</view>
			
			<!-- 搜索框 -->
			<view class="search-section">
				<view class="search-box">
					<text class="search-icon">S</text>
					<input 
						v-model="searchKeyword"
						type="text" 
						placeholder="搜索好友"
						class="search-input"
						@input="onSearchInput"
					/>
					<text v-if="searchKeyword" class="clear-btn" @click="clearSearch">×</text>
				</view>
			</view>
			
			<!-- 好友列表 -->
			<view class="friends-section">
				<view class="section-header">
					<text class="section-title">我的好友 ({{ filteredFriends.length }})</text>
					<text class="manage-btn" @click="toggleManageMode">{{ isManageMode ? '完成' : '管理' }}</text>
				</view>
				
				<view class="friends-list">
					<view 
						v-for="friend in filteredFriends" 
						:key="friend.id"
						class="friend-item"
						@click="openChat(friend)"
					>
						<view v-if="isManageMode" class="select-checkbox" @click.stop="toggleSelect(friend)">
							<text class="checkbox-icon">{{ friend.selected ? '✓' : '' }}</text>
						</view>

						<image
							:src="friend.avatar || 'https://ts1.tc.mm.bing.net/th/id/OIP-C.4qE6UmzbSk0mCOn2uWMELAAAAA?rs=1&pid=ImgDetMain&o=7&rm=3'"
							class="friend-avatar"
							mode="aspectFill"
							@click.stop="openFriendProfile(friend)"
							@error="onAvatarError"
						/>
						
						<view class="friend-info">
							<text class="friend-name">{{ friend.nickname || friend.realName || friend.username }}</text>
							<text class="friend-desc">{{ friend.remark || '暂无备注' }}</text>
						</view>
						
						<view class="friend-status">
							<text v-if="friend.isOnline" class="online-dot">●</text>
							<text class="status-text">{{ friend.isOnline ? '在线' : '离线' }}</text>
						</view>
					</view>
				</view>
				
				<!-- 空状态 -->
				<view v-if="filteredFriends.length === 0" class="empty-state">
					<ob-empty 
						:image="'/static/images/empty-friends.png'"
						title="暂无好友"
						description="添加好友开始聊天吧"
					/>
					<button class="add-friend-btn" @click="goToAddFriend">添加好友</button>
				</view>
			</view>
			
			<!-- 管理操作栏 -->
			<view v-if="isManageMode && selectedFriends.length > 0" class="manage-actions">
				<button class="action-btn delete" @click="batchDeleteFriends">删除好友</button>
			</view>
		</view>
		
		<!-- 加载组件 -->
		<ob-loading :visible="isLoading" text="加载中..." />
		
		<!-- 用户信息弹窗 -->
		<view v-if="showUserInfoModal" class="user-info-modal" @click="closeUserInfoModal">
			<view class="modal-content" @click.stop>
				<view class="modal-header">
					<text class="modal-title">用户信息</text>
					<text class="close-btn" @click="closeUserInfoModal">×</text>
				</view>
				
				<view class="modal-body">
					<view class="user-avatar-section">
						<image
							:src="selectedUserInfo?.avatar || 'https://ts1.tc.mm.bing.net/th/id/OIP-C.4qE6UmzbSk0mCOn2uWMELAAAAA?rs=1&pid=ImgDetMain&o=7&rm=3'"
							class="modal-avatar"
							mode="aspectFill"
							@error="onAvatarError"
						/>
						<text class="user-main-name">{{ selectedUserInfo?.nickname || selectedUserInfo?.realName || selectedUserInfo?.username }}</text>
					</view>
					
					<view class="user-info-list">
						<view class="info-item">
							<text class="info-label">用户名</text>
							<text class="info-value">{{ selectedUserInfo?.username || '未设置' }}</text>
						</view>
						<view class="info-item">
							<text class="info-label">昵称</text>
							<text class="info-value">{{ selectedUserInfo?.nickname || '未设置' }}</text>
						</view>
						<view class="info-item">
							<text class="info-label">真实姓名</text>
							<text class="info-value">{{ selectedUserInfo?.realName || '未设置' }}</text>
						</view>
						<view class="info-item">
							<text class="info-label">手机号</text>
							<text class="info-value">{{ selectedUserInfo?.phone || '未设置' }}</text>
						</view>
						<view class="info-item">
							<text class="info-label">验证状态</text>
							<text class="info-value" :class="selectedUserInfo?.emailVerified === 1 ? 'verified' : 'unverified'">
								{{ selectedUserInfo?.emailVerified === 1 ? '已验证' : '未验证' }}
							</text>
						</view>
					</view>
				</view>
				
				<view class="modal-footer">
					<button class="modal-btn primary" @click="openChat(selectedUserInfo)">发送消息</button>
					<button class="modal-btn danger" @click="deleteSingleFriend(selectedUserInfo)">删除好友</button>
					<button class="modal-btn secondary" @click="closeUserInfoModal">关闭</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import friendApi from '../../api/friend.js'

// 响应式数据
const friends = ref([])
const searchKeyword = ref('')
const pendingRequests = ref(0)
const isLoading = ref(false)
const isManageMode = ref(false)
const showUserInfoModal = ref(false)
const selectedUserInfo = ref(null)

// 计算属性
const filteredFriends = computed(() => {
	if (!searchKeyword.value.trim()) {
		return friends.value
	}
	
	const keyword = searchKeyword.value.toLowerCase()
	return friends.value.filter(friend => {
		const name = (friend.nickname || friend.realName || friend.username || '').toLowerCase()
		const remark = (friend.remark || '').toLowerCase()
		return name.includes(keyword) || remark.includes(keyword)
	})
})

const selectedFriends = computed(() => {
	return friends.value.filter(friend => friend.selected)
})

// 生命周期
onMounted(() => {
	loadFriends()
	loadPendingRequests()
})

// 方法
const loadFriends = async () => {
	try {
		isLoading.value = true
		const response = await friendApi.getFriendList()
		console.log('好友列表响应数据:', response)

		// 确保response是数组
		const friendsData = Array.isArray(response) ? response : (response?.data || [])
		friends.value = friendsData.map(friend => ({
			...friend,
			selected: false,
			// 确保显示字段存在
			id: friend.id,
			nickname: friend.nickname || friend.realName || friend.username,
			avatar: friend.avatar,
			remark: friend.remark || '',
			isOnline: friend.isOnline || false
		}))

		console.log('处理后的好友数据:', friends.value)
	} catch (error) {
		console.error('加载好友列表失败:', error)
		uni.showToast({
			title: '加载失败',
			icon: 'none'
		})
	} finally {
		isLoading.value = false
	}
}

const loadPendingRequests = async () => {
	try {
		const response = await friendApi.getFriendRequestCount()
		// 确保正确提取数值，避免显示完整的JSON对象
		const count = typeof response === 'number' ? response : (response?.data ?? 0)
		pendingRequests.value = count
		console.log('待验证的好友数量', pendingRequests.value)
	} catch (error) {
		console.error('加载好友申请数量失败:', error)
		// 出错时设置为0
		pendingRequests.value = 0
	}
}

const onSearchInput = () => {
	// 实时搜索
}

const clearSearch = () => {
	searchKeyword.value = ''
}

const toggleManageMode = () => {
	isManageMode.value = !isManageMode.value
	if (!isManageMode.value) {
		// 退出管理模式，清除选择
		friends.value.forEach(friend => {
			friend.selected = false
		})
	}
}

const toggleSelect = (friend) => {
	friend.selected = !friend.selected
}

// 打开好友个人详情弹窗
const openFriendProfile = (friend) => {
	if (isManageMode.value) return
	
	// 设置选中的用户信息
	selectedUserInfo.value = friend
	showUserInfoModal.value = true
}

// 关闭用户信息弹窗
const closeUserInfoModal = () => {
	showUserInfoModal.value = false
	selectedUserInfo.value = null
}

// 打开聊天页面
const openChat = (friend) => {
	if (isManageMode.value) return

	// 获取好友的用户信息
	const friendUserInfo = friend.friendUserInfo || friend
	const friendId = friendUserInfo?.id || friend.id
	const friendUsername = friendUserInfo?.username || friend.username
	const friendName = friendUserInfo?.nickname || friendUserInfo?.realName || friend.nickname || friend.realName || friendUsername
	const friendAvatar = friendUserInfo?.avatar || friend.avatar || ''

	console.log('打开聊天:', { friend, friendId, friendUsername, friendName })

	// 传递用户ID到聊天页面
	uni.navigateTo({
		url: `/pages/message/chat?type=private&name=${encodeURIComponent(friendUsername)}&username=${encodeURIComponent(friendUsername)}&nickname=${encodeURIComponent(friendName)}&avatar=${encodeURIComponent(friendAvatar)}&toUserId=${friendId}`
	})
}

const goToRequests = () => {
	uni.navigateTo({
		url: '/pages/message/friend-requests'
	})
}

const goToAddFriend = () => {
	uni.navigateTo({
		url: '/pages/message/add-friend'
	})
}

const batchDeleteFriends = () => {
	if (selectedFriends.value.length === 0) return
	
	uni.showModal({
		title: '删除好友',
		content: `确定要删除选中的${selectedFriends.value.length}个好友吗？`,
		confirmText: '删除',
		cancelText: '取消',
		confirmColor: '#ff4757',
		success: async (res) => {
			if (res.confirm) {
				try {
					// 批量删除好友
					const deletePromises = selectedFriends.value.map(friend => 
						friendApi.deleteFriend(friend.id)
					)
					await Promise.all(deletePromises)
					
					// 从列表中移除
					friends.value = friends.value.filter(friend => !friend.selected)

					// 退出管理模式
					isManageMode.value = false

					uni.showToast({
						title: '删除成功',
						icon: 'success'
					})
				} catch (error) {
					console.error('删除好友失败:', error)
					uni.showToast({
						title: '删除失败',
						icon: 'none'
					})
				}
			}
		}
	})
}

// 删除单个好友
const deleteSingleFriend = (friend) => {
	uni.showModal({
		title: '删除好友',
		content: `确定要删除好友"${friend.nickname || friend.realName || friend.username}"吗？`,
		confirmText: '删除',
		cancelText: '取消',
		confirmColor: '#ff4757',
		success: async (res) => {
			if (res.confirm) {
				try {
					// 删除好友
					await friendApi.deleteFriend(friend.id)

					// 从列表中移除
					friends.value = friends.value.filter(f => f.id !== friend.id)

					// 关闭弹窗
					closeUserInfoModal()

					uni.showToast({
						title: '删除成功',
						icon: 'success'
					})
				} catch (error) {
					console.error('删除好友失败:', error)
					uni.showToast({
						title: '删除失败',
						icon: 'none'
					})
				}
			}
		}
	})
}

// 头像加载错误处理
const onAvatarError = (e) => {
	console.log('好友头像加载失败，使用默认头像')
	e.target.src = 'https://ts1.tc.mm.bing.net/th/id/OIP-C.4qE6UmzbSk0mCOn2uWMELAAAAA?rs=1&pid=ImgDetMain&o=7&rm=3'
}

</script>

<style lang="scss" scoped>
.friends-page {
	background: #FAFAFA;
	min-height: 100vh;
}

.content {
	padding: 0;
}

.request-notice {
	background: #FFFFFF;
	margin: 15px;
	border-radius: 8px;
	padding: 15px 20px;
	display: flex;
	align-items: center;
	border-left: 3px solid #495057;
	
	&:active {
		background: #F8F9FA;
	}
}

.notice-icon {
	width: 40px;
	height: 40px;
	background: #F8F9FA;
	border: 1px solid #E9ECEF;
	border-radius: 20px;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 16px;
	font-weight: 600;
	color: #6C757D;
	margin-right: 15px;
}

.notice-info {
	flex: 1;
}

.notice-title {
	font-size: 16px;
	color: #333333;
	font-weight: 500;
	display: block;
	margin-bottom: 4px;
}

.notice-desc {
	font-size: 12px;
	color: #999999;
}

.notice-arrow {
	font-size: 16px;
	color: #CED4DA;
}

.search-section {
	background: #FFFFFF;
	padding: 15px 20px;
	margin: 0 15px 15px;
	border-radius: 8px;
}

.search-box {
	position: relative;
	display: flex;
	align-items: center;
}

.search-icon {
	font-size: 14px;
	font-weight: 600;
	color: #6C757D;
	margin-right: 8px;
}

.search-input {
	flex: 1;
	background: #F8F9FA;
	border: 1px solid #E9ECEF;
	border-radius: 20px;
	padding: 8px 15px;
	font-size: 14px;
	height: 36px;
	box-sizing: border-box;
}

.clear-btn {
	position: absolute;
	right: 15px;
	font-size: 16px;
	color: #999999;
	width: 20px;
	text-align: center;
}

.friends-section {
	background: #FFFFFF;
	margin: 0 15px 15px;
	border-radius: 8px;
	padding: 0;
}

.section-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 15px 20px;
	border-bottom: 1px solid #F0F0F0;
}

.section-title {
	font-size: 16px;
	font-weight: 600;
	color: #333333;
}

.manage-btn {
	font-size: 14px;
	color: #6C757D;
}

.friends-list {
	padding: 0;
}

.friend-item {
	display: flex;
	align-items: center;
	padding: 15px 20px;
	border-bottom: 1px solid #F8F9FA;
	position: relative;
	
	&:last-child {
		border-bottom: none;
	}
	
	&:active {
		background: #F8F9FA;
	}
}

.select-checkbox {
	width: 20px;
	height: 20px;
	border: 1px solid #DEE2E6;
	border-radius: 4px;
	margin-right: 15px;
	display: flex;
	align-items: center;
	justify-content: center;
	
	&:active {
		background: #F8F9FA;
	}
}

.checkbox-icon {
	font-size: 14px;
	color: #28A745;
	font-weight: 600;
}

.friend-avatar {
	width: 50px;
	height: 50px;
	border-radius: 25px;
	margin-right: 15px;
}

.friend-info {
	flex: 1;
	min-width: 0;
}

.friend-name {
	font-size: 16px;
	font-weight: 500;
	color: #333333;
	display: block;
	margin-bottom: 4px;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.friend-desc {
	font-size: 12px;
	color: #999999;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.friend-status {
	display: flex;
	align-items: center;
	flex-shrink: 0;
}

.online-dot {
	font-size: 8px;
	color: #28A745;
	margin-right: 4px;
}

.status-text {
	font-size: 12px;
	color: #999999;
}

.empty-state {
	padding: 40px 20px;
	text-align: center;
}

.add-friend-btn {
	background: #F8F9FA;
	border: 1px solid #E9ECEF;
	color: #6C757D;
	padding: 10px 20px;
	border-radius: 20px;
	font-size: 14px;
	margin-top: 20px;
}

.manage-actions {
	position: fixed;
	bottom: 34px;
	left: 15px;
	right: 15px;
	background: #FFFFFF;
	border-radius: 8px;
	padding: 15px;
	box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
	display: flex;
	gap: 15px;
}

.action-btn {
	flex: 1;
	padding: 12px;
	border-radius: 6px;
	font-size: 14px;
	font-weight: 500;
	border: 1px solid #DEE2E6;
	
	&.delete {
		background: #FFF5F5;
		color: #DC3545;
		border-color: #DC3545;
	}
	
	&.move {
		background: #F8F9FA;
		color: #6C757D;
		border-color: #E9ECEF;
	}
}

// 用户信息弹窗样式
.user-info-modal {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.5);
	display: flex;
	align-items: center;
	justify-content: center;
	z-index: 9999;
	padding: 20px;
}

.modal-content {
	background: #FFFFFF;
	border-radius: 12px;
	width: 100%;
	max-width: 400px;
	max-height: 80vh;
	overflow: hidden;
}

.modal-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20px;
	border-bottom: 1px solid #F0F0F0;
}

.modal-title {
	font-size: 18px;
	font-weight: 600;
	color: #333333;
}

.close-btn {
	font-size: 24px;
	color: #999999;
	width: 30px;
	height: 30px;
	display: flex;
	align-items: center;
	justify-content: center;
	border-radius: 15px;
	
	&:active {
		background: #F8F9FA;
	}
}

.modal-body {
	padding: 20px;
	max-height: 60vh;
	overflow-y: auto;
}

.user-avatar-section {
	display: flex;
	flex-direction: column;
	align-items: center;
	margin-bottom: 20px;
}

.modal-avatar {
	width: 80px;
	height: 80px;
	border-radius: 40px;
	margin-bottom: 12px;
}

.user-main-name {
	font-size: 20px;
	font-weight: 600;
	color: #333333;
}

.user-info-list {
	display: flex;
	flex-direction: column;
	gap: 12px;
}

.info-item {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 12px 0;
	border-bottom: 1px solid #F8F9FA;
	
	&:last-child {
		border-bottom: none;
	}
}

.info-label {
	font-size: 14px;
	color: #666666;
	flex-shrink: 0;
	width: 80px;
}

.info-value {
	font-size: 14px;
	color: #333333;
	flex: 1;
	text-align: right;
	
	&.verified {
		color: #28A745;
	}
	
	&.unverified {
		color: #DC3545;
	}
}

.modal-footer {
	display: flex;
	gap: 12px;
	padding: 20px;
	border-top: 1px solid #F0F0F0;
}

.modal-btn {
	flex: 1;
	padding: 12px;
	border-radius: 8px;
	font-size: 14px;
	font-weight: 500;
	border: 1px solid #E9ECEF;
	
	&.primary {
		background: #F8F9FA;
		color: #495057;
		border-color: #ADB5BD;
	}
	
	&.secondary {
		background: #FFFFFF;
		color: #6C757D;
		border-color: #E9ECEF;
	}

	&.danger {
		background: #DC3545;
		color: #FFFFFF;
		border-color: #DC3545;
	}

	&:active {
		opacity: 0.8;
	}
}
</style>